package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.dto.request.agent.ApplyRequest;
import cn.edu.ncu.housinghub.entity.user.AgentVerification;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.AgentMapper;
import cn.edu.ncu.housinghub.service.AgentAuthService;
import cn.edu.ncu.housinghub.utils.common.TokenUtil;
import cn.edu.ncu.housinghub.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AgentAuthServiceImpl implements AgentAuthService {
    @Autowired
    private AgentMapper agentMapper;
    @Override
    public Result apply(ApplyRequest applyRequest, String token) {
        // 根据token获取用户信息
        User user = TokenUtil.getUserByToken(token);
        // 如果token 无效
        if (user == null) {
            throw new BusinessException(ErrorCodeConstant.INVALID_TOKEN);
        }
        // 如果用户未实名认证
        if (!user.getIsIdentityVerified()) {
            throw new BusinessException(ErrorCodeConstant.USER_DONT_VERIFIED);
        }
        // 如果用户不是普通用户类型
        if (user.getRole() != 1) {
            throw new BusinessException(ErrorCodeConstant.USER_HAS_OTHER_ROLE);
        }
        // 检查用户是否有未删除的申请记录
        AgentVerification existingApply = agentMapper.selectApplyResult(user.getId());
        if (existingApply != null) {
            // 如果有待审核或已通过的申请，不允许重新申请
            if (existingApply.getVerifyStatus() == 1 || existingApply.getVerifyStatus() == 2) {
                throw new BusinessException(ErrorCodeConstant.APPLY_ALREADY);
            }
            // 如果是被拒绝的申请，软删除之前的记录，允许重新申请
            if (existingApply.getVerifyStatus() == 0) {
                agentMapper.softDeleteApplyByUserId(user.getId());
                System.out.println("🔄 用户重新申请中介，已软删除之前被拒绝的申请记录，用户ID: " + user.getId());
            }
        }

        // 检查营业执照编号是否已被其他用户使用（未删除的记录）
        AgentVerification licenseApply = agentMapper.selectApplyByLicenseNo(applyRequest.getLicenseNo());
        if (licenseApply != null && !licenseApply.getUserId().equals(user.getId()) && licenseApply.getVerifyStatus() != 0) {
            throw new BusinessException(ErrorCodeConstant.BUSINESS_LICENSE_ALREADY_APPLY);
        }
        // 验证营业执照编号格式
        String licenseNo = applyRequest.getLicenseNo();
        if (licenseNo == null || licenseNo.trim().isEmpty()) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR);
        }

        // 验证营业执照编号长度和格式
        licenseNo = licenseNo.trim().toUpperCase();
        if (licenseNo.length() != 18) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR);
        }

        if (!licenseNo.matches("^[0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}$")) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR);
        }

       /* // 检查营业执照编号是否已被使用
        AgentVerification existingApplication = agentMapper.selectApplyByLicenseNo(licenseNo);
        if (existingApplication != null && !existingApplication.getIsDeleted()) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "该营业执照编号已被使用，请检查后重新输入");
        }*/

        // 将申请信息保存到数据库中
        try {
            AgentVerification agentVerification = new AgentVerification();
            agentVerification.setUserId(user.getId());
            agentVerification.setLicenseNo(licenseNo); // 使用处理后的营业执照编号
            agentVerification.setLicensePicPath(applyRequest.getLicensePicPath());
            agentVerification.setPhone(applyRequest.getPhone());
            agentVerification.setCompanyName(applyRequest.getCompanyName());
            agentVerification.setCompanyPosition(applyRequest.getCompanyPosition());
            agentVerification.setRealName(applyRequest.getRealName());
            agentVerification.setIdCard(applyRequest.getIdCard());
            agentVerification.setEmail(applyRequest.getEmail());
            agentVerification.setCity(applyRequest.getCity());
            agentVerification.setWorkYears(applyRequest.getWorkYears());
            agentVerification.setApplyTime(LocalDateTime.now());
            agentVerification.setVerifyStatus(SystemConstant.AGENT_VERIFY_STATUS_PENDING.getIntegerValue()); // 设置为审核中
            agentVerification.setIsDeleted(false);
            agentMapper.insertApply(agentVerification);
            return Result.success("申请信息存储成功！");
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // 处理数据库字段长度或约束违反错误
            String errorMessage = e.getMessage();
            if (errorMessage.contains("Data truncated for column 'licenseNo'")) {
                throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "营业执照编号长度超出限制，请检查输入");
            } else if (errorMessage.contains("licenseNo")) {
                throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "营业执照编号格式错误或已存在");
            } else {
                throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "数据保存失败，请检查输入信息");
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "申请提交失败：" + e.getMessage());
        }
    }

    @Override
    public Result findApplyResult(String token) {
        // 根据token获取用户信息
        User user = TokenUtil.getUserByToken(token);
        // 如果token 无效
        if (user == null) {
            return Result.error(ErrorCodeConstant.INVALID_TOKEN.getCode(), ErrorCodeConstant.INVALID_TOKEN.getMessage());
        }
        // 返回申请结果
        return Result.success(agentMapper.selectApplyResult(user.getId()));
    }

}
